package com.xin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xin.constant.MessageConstant;
import com.xin.constant.RedisConstant;
import com.xin.entity.PageResult;
import com.xin.entity.QueryPageBean;
import com.xin.entity.Result;
import com.xin.pojo.Setmeal;
import com.xin.service.SetmealService;
import com.xin.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

import static com.xin.constant.MessageConstant.*;

/**
 * @Author 夜天
 * @Date 2021/12/16 10:30
 * @Version 1.0.0
 * @description： 体检套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetmealService setmealService;
    // 文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        // 原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        // 获取文件后缀
        String ex = originalFilename.substring(index - 1);
        // 使用UUID随机产生文件名称，防止同名文件覆盖
        String fileName = UUID.randomUUID().toString() + ex;
        try{
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //图片上传成功
            Result result = new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS);
            result.setData(fileName);
            //将上传图片名称存入Redis，基于Redis的Set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

            return result;

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,PIC_UPLOAD_FAIL);
        }
    }
    // 新增套餐
    @RequestMapping("/add")
    public Result add(Setmeal setmeal,Integer[] checkgroupIds){
        try{
            setmealService.add(setmeal,checkgroupIds);
        }catch(Exception e){
            // 新增套餐失败
            e.printStackTrace();
            return new Result(false,ADD_SETMEAL_FAIL);
        }
        // 新增套餐成功
        return new Result(true,ADD_SETMEAL_SUCCESS);
    }
    // 分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = setmealService.pageQuery(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString()
        );
        return pageResult;
    }
}
